package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CaptchaResponse;
import com.pn.taikao.service.CaptchaService;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

    private final CaptchaService captchaService;

    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    /**
     * 获取验证码图片
     * @return 验证码Key和Base64编码的图片
     */
    @GetMapping
    public ApiResponse<CaptchaResponse> getCaptcha() {
        // 生成唯一标识
        String captchaKey = UUID.randomUUID().toString().replace("-", "");
        
        // 生成验证码图片
        BufferedImage image = captchaService.generateCaptchaImage(captchaKey);
        
        // 将图片转换为Base64
        String imageBase64;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            return ApiResponse.error("生成验证码失败");
        }
        
        CaptchaResponse response = new CaptchaResponse(captchaKey, "data:image/png;base64," + imageBase64);
        return ApiResponse.success(response);
    }
}

